import os
import random
from fileinput import filename
from time import sleep

import cv2
import pyautogui
import pygetwindow as gw
import time
import numpy as np
from pyautogui import click


def find_window():
    target_window_title = "跳一跳"
    target_window = gw.getWindowsWithTitle(target_window_title)
    if target_window:
        # print(f"找到窗口：{target_window_title}")
        window = target_window[0]
        return window
    else:
        print("未找到该窗口！")

def take_screenshot(window):
    left = window.left + 13
    top = window.top + 5
    width = window.width - 25
    height = window.height - 15

    screenshot = pyautogui.screenshot(region=(left, top, width, height))
    # print(left,top,width,height)
    screenshot.save("1.png")
    # print("截图已保存为 1.png")
    return left,top

def click_mouse(screen_left,screen_top,tm):
    randX = random.randint(0,440)
    randY = random.randint(0,208)
    mouse_left = screen_left + randX
    mouse_top = screen_top + 50 + randY
    #不在一个坐标重复点击，随机点击某一个坐标
    pyautogui.moveTo(mouse_left, mouse_top)

    pyautogui.mouseDown()
    time.sleep(tm)
    pyautogui.mouseUp()
    # time.sleep(1)

#定位跳棋
def get_player(img,player_template):
    player = cv2.matchTemplate(img, player_template, cv2.TM_CCOEFF_NORMED)
    # 获取匹配结果中的最小值、最大值、最小值坐标和最大值坐标
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(player)

    corner_loc = (max_loc[0] + 37, max_loc[1] + 88)
    player_spot = (max_loc[0] + 18, max_loc[1] + 88)
    cv2.circle(img, player_spot, 10, (0, 255, 255), -1)
    cv2.rectangle(img, max_loc, corner_loc, (0,0,255), 5)

    return img,player_spot,max_loc

#定位跳台
# def get_center(image,max_loc, test ):
def get_center(image, max_loc):
    # image = cv2.imread('images/5.png')
    blurred_img = cv2.GaussianBlur(image, (5, 5), 0)  # 高斯模糊
    canny_img = cv2.Canny(blurred_img, 1, 10)  # 边缘检测

    height, width = canny_img.shape
    crop_img = canny_img[300:int(height / 2), 0:width]

    # #消除小跳棋 根据跳棋的坐标，消除跳棋附近范围的
    # for y in range(max_loc[1], max_loc[1]-150):
    #     for x in range(max_loc[0], max_loc[0] + 50):
    #         canny_img[y][x] = 0

    # 获取中心点坐标
    crop_h, crop_w = crop_img.shape
    center_x, center_y = 0, 0
    max_x = 0
    for y in range(crop_h):
        for x in range(crop_w):
            if crop_img[y, x] == 255:
                if center_x == 0:
                    center_x = x
                if x > max_x:
                    center_y = y
                    max_x = x

    # if test == 1 :
    #     center_y = center_y - 17
    cv2.circle(crop_img, (center_x, center_y), 10, 255, -1)
    # cv2.imshow('crop_img', crop_img)
    center_y = center_y + 300
    cv2.circle(image, (center_x, center_y), 10, 255, -1)
    # cv2.imshow('Img', image)
    return image,center_x,center_y,crop_img

def main():
    save_folder = r'D:\biancheng\PyCharm Community Edition 2024\pythonProject\save'
    for filename in os.listdir(save_folder):
        file_path = os.path.join(save_folder, filename)
        os.remove(file_path)
    first_num = 1
    second_num = 1
    txt = 1
    num = 1
    while True:
        time.sleep(1)
        test = 0
        window = find_window()
        if window:
            left,top = take_screenshot(window)
        image = cv2.imread("1.png")  # 读取原始图像
        img = image
        x, y =img.shape[:2]
        player_template = cv2.imread("people.png")  # 读取跳棋模板图像
        gameover_template = cv2.imread("gameover.png")  # 读取游戏结束模板图像
        rest_template = cv2.imread("rest.png")  # 读取休息一下模板图像

        res_end = cv2.matchTemplate(img, gameover_template, cv2.TM_CCOEFF_NORMED)
        _, end_max_val, _, _ = cv2.minMaxLoc(res_end)

        res_rest = cv2.matchTemplate(img, rest_template, cv2.TM_CCOEFF_NORMED)
        _, rest_max_val, _, _ = cv2.minMaxLoc(res_rest)
        if end_max_val> 0.5 or rest_max_val > 0.5:
            print("----------One More time------------")
            first_num += 1
            txt += 1
            time.sleep(3)
            pyautogui.click(1623, 711)
            continue
        img,player_spot,max_loc = get_player(img, player_template)
        # if player_spot[0] > 240:
        #     player_spot = y - player_spot[0],player_spot[1]
        #     img = cv2.flip(img, 1)
        #     test = 1

        # img,center_x,center_y,crop_img= get_center(image, player_spot, test)
        img,center_x,center_y,crop_img= get_center(image, player_spot)
        # cv2.imshow('Img', img)
        # print(player_spot[0],player_spot[1])
        # print(center_x,center_y)
        distance = (player_spot[0] - center_x) ** 2 + (player_spot[1] - center_y) ** 2
        distance = distance ** 0.5
        # print("distance:", distance )

        # if distance < 178:
        #     tm = 0.45 * distance / 161.07451691686057
        # else:
        #     # tm = float(input())
        #     tm = 0.70 * distance / 225.21101216414795
        if distance < 255 and distance > 150:
            tm = 0.45 * distance / 161.07451691686057
        elif distance > 255:
            tm = 0.82 * distance / 283.6688209867274
        else :
            tm = 0.34 * distance/128.41339493993607

        # 按下鼠标左键
        # if (distance < 100):
        if distance:
            print("distance:", distance)
            print(tm)
            # 指定要保存的文件名
            txtname = os.path.join(save_folder, f'value{txt}.txt')
            # 打开文件，准备写入
            with open(txtname, 'a') as file:
                # 写入 distance 的值
                file.write(str(txt) + "_" + str(num) + ": "  +    str(distance) + "    "+ str(tm) + "\n")

            # 构建文件名，包括路径和文件名
            filename = f'{save_folder}\\img{first_num}_{second_num}.png'
            filename2 = f'{save_folder}\\cropImg{first_num}_{second_num}.png'
            # cv2.imwrite('img'+str(num) +'.png', img)
            # cv2.imwrite('cropImg' + str(num) + '.png', crop_img)
            cv2.imwrite(filename,img)
            cv2.imwrite(filename2,crop_img)
            second_num += 1
            num += 1
        click_mouse(left,top,tm)
        time.sleep(1.3)

        # cv2.waitKey(0)
        # cv2.destroyAllWindows()


if __name__ == '__main__':
    main()